package com.gmail.hongyz.myfuse.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.gmail.hongyz.myfuse.model.User;
import com.gmail.hongyz.myfuse.service.UserService;

public class LoginController implements Controller {

	private static final Log log = LogFactory.getLog(LoginController.class);
	
	private UserService userService;
	
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		if (log.isDebugEnabled()) {
            log.debug("entering 'handleRequest' method...");
        }
		String userId = request.getParameter("userId");
		String password = request.getParameter("password");
		log.debug("userId: " + userId);
		log.debug("password: " + password);
		User user = userService.getUserByUserId(userId);
		log.debug("user: " + user);
		if (user == null) {
			return null;
		}
		boolean login = user.validatePassword(password);
		log.info("login: " + login);
		if (login) {
			request.getSession().setAttribute("user", user);
			return new ModelAndView("main");
		} else {
			return null;
		}
		
	}
}
